mui.init();

var subpages = ['home.html', 'live.html', 'channel.html', 'my.html'];
var subpage_style = {
	top: '44px',
	bottom: '44px'
};

var subpage_style_setting = {
	top: '0',
	bottom: '44px'
};

var aniShow = {};

//创建子页面，首个选项卡页面显示，其它均隐藏；
mui.plusReady(function() {
	var self = plus.webview.currentWebview();
	for(var i = 0; i < 4; i++) {
		var temp = {};
		var sub;
		if(i === 3) {
			sub = plus.webview.create(subpages[i], subpages[i], subpage_style_setting);
		} else {
			sub = plus.webview.create(subpages[i], subpages[i], subpage_style);
		}
		if(i > 0) {
			sub.hide();
		} else {
			temp[subpages[i]] = "true";
			mui.extend(aniShow, temp);
		}
		self.append(sub);
	}

	//打开搜索页
	openSearch();

	//当前激活选项
	var activeTab = subpages[0];
	var title = document.getElementById("title");
	//选项卡点击事件
	mui('.mui-bar-tab').on('tap', 'a', function(e) {
		var targetTab = this.getAttribute('href');
		if(targetTab == activeTab) {
			return;
		}
		//更换标题
		title.innerHTML = this.querySelector('.mui-tab-label').innerHTML;
		//显示目标选项卡
		//若为iOS平台或非首次显示，则直接显示
		if(mui.os.ios || aniShow[targetTab]) {
			plus.webview.show(targetTab);
		} else {
			//否则，使用fade-in动画，且保存变量
			var temp = {};
			temp[targetTab] = "true";
			mui.extend(aniShow, temp);
			plus.webview.show(targetTab, "fade-in", 300);
		}
		//隐藏当前;
		plus.webview.hide(activeTab);
		//更改当前活跃的选项卡
		activeTab = targetTab;
	});
	//自定义事件，模拟点击“首页选项卡”
	document.addEventListener('gohome', function() {
		var defaultTab = document.getElementById("defaultTab");
		//模拟首页点击
		mui.trigger(defaultTab, 'tap');
		//切换选项卡高亮
		var current = document.querySelector(".mui-bar-tab>.mui-tab-item.mui-active");
		if(defaultTab !== current) {
			current.classList.remove('mui-active');
			defaultTab.classList.add('mui-active');
		}
	});

});

//打开搜索页面
function openSearch() {
	var search_btn = document.getElementById('search_btn');
	search_btn.addEventListener('tap', function() {
		var search_page = plus.webview.getWebviewById('search.html');
		if(!search_page) {
			search_page = plus.webview.create('search.html', 'search.html', {}, {
				name: 'Noodlewar'
			});
		}
		plus.webview.show(search_page, 'slide-in-right');
	})
}